import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
import Components from 'unplugin-vue-components/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import { loadEnv } from 'vite';
import { viteMockServe } from 'vite-plugin-mock';


export default ({ command, mode }) => {
  const root = process.cwd();
  console.log("viteConfig--root:", root);

  const env = loadEnv(mode, root);
  console.log("viteConfig--mode", env);

  return {
    plugins: [
      vue(),
      // 按需引入
      Components({
        resolvers: [
          AntDesignVueResolver(),
        ]
      }),
      // mock
      viteMockServe({
        logger: true,
        mockPath: "./mock/"
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
      }
    },
    server: {
      port: 8888,
      host: '0.0.0.0',
      hmr: {
        overlay: true
      },
      proxy: {
        "/api": {
          // target: "http://localhost:9999",
          // rewrite: (path) => path.replace(/^\/api/, ''),
          // changeOrigin: true,
          target: "http://test.zhaoshej.com",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '\/api/')
        },
      },
    },
    // build: {
    //   sourcemap: false,
    //   //polyfillDynamicImport: false, // 必须为false
    //   // rollupOptions: {
    //   //   output: {
    //   //     manualChunks: {
    //   //       antdesin: ['ant-design-vue'],
    //   //       vue3videoplay: ['vue3-video-play'],
    //   //       tiptap: ['@tiptap/vue-3'],
    //   //       cosjssdk: ['cos-js-sdk-v5'],
    //   //       antdesignicons: ['@ant-design/icons-vue'],
    //   //     }
    //   //   }
    //   // }
    //   // rollupOptions: {
    //   //   input: {
    //   //     main: path.resolve(__dirname, 'index.html'),
    //   //     mobile: path.resolve(__dirname, 'mobile/index.html')
    //   //   }
    //   // }
    // },
  }
};

const httpsRE = /^https:\/\//;
/**
 * Generate proxy
 * @param list
 */
function createProxy(list) {
  const ret = {};
  for (const [prefix, target] of list) {
    const isHttps = httpsRE.test(target);

    // https://github.com/http-party/node-http-proxy#options
    ret[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
      // https is require secure=false
      ...(isHttps ? { secure: false } : {}),
    };
  }
  return ret;
}